package biz

import (
	"context"
	"manage/api/course"
	"manage/internal/errors"
	"net/http"

	"github.com/gin-gonic/gin"
)

func (u *APIUseCase) Course() *Method {
	remoteName := "课程服务"
	remoteCourse := u.Repo.Course

	return &Method{
		Get: func(c *gin.Context) {
			courseID := c.Param("course_id")

			remoteCourse(func(ctx context.Context, csc course.CourseServiceClient) {
				reply, err := csc.GetCourse(ctx, &course.GetCourseRequest{
					CourseId: courseID,
				})
				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.CourseInfo,
					})
				}
			})
		},

		Post: func(c *gin.Context) {
			courseName := c.PostForm("course_name")
			courseDescription := c.PostForm("course_description")

			remoteCourse(func(ctx context.Context, csc course.CourseServiceClient) {
				reply, err := csc.CreateCourse(ctx, &course.CreateCourseRequest{
					CourseName:        courseName,
					CourseDescription: courseDescription,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.CourseId,
					})
				}
			})
		},

		Put: func(c *gin.Context) {
			courseID := c.Param("course_id")
			courseName := c.PostForm("course_name")
			courseDescription := c.PostForm("course_description")

			remoteCourse(func(ctx context.Context, csc course.CourseServiceClient) {
				reply, err := csc.UpdateCourse(ctx, &course.UpdateCourseRequest{
					CourseId:          courseID,
					CourseName:        courseName,
					CourseDescription: courseDescription,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
					})
				}
			})
		},

		Delete: func(c *gin.Context) {
			courseID := c.Param("course_id")

			remoteCourse(func(ctx context.Context, csc course.CourseServiceClient) {
				reply, err := csc.DeleteCourse(ctx, &course.DeleteCourseRequest{
					CourseId: courseID,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
					})
				}
			})
		},
	}
}
